package handler

import (
	"encoding/json"
	"matrix/backend/db"
	"matrix/backend/util"
	"net/http"
	"time"
)

// RegisterHandler : 用户注册
func RegisterHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	userName := r.Form.Get("userName")
	userPwd := r.Form.Get("userPwd")
	var message util.RegisterMessage
	message.UserName = userName
	if userName != "" && userPwd != "" {
		message.Status = db.Register(userName, userPwd)
		if message.Status == 0 {
			message.RegisterTime = time.Now().Format("2006-01-02 15:04:05")
		}
	} else {
		message.Status = 1
	}
	// 返回注册结果
	data, _ := json.Marshal(message)
	w.Header().Set("content-type", "text/json")
	w.Write(data)
}

// LoginHandler : 用户登录
func LoginHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	userName := r.Form.Get("userName")
	userPwd := r.Form.Get("userPwd")
	userPwd, _ = util.EnPwdCode([]byte(userPwd))
	var message util.LoginMessage
	message.UserName = userName
	if userName != "" && userPwd != "" {
		message.UserToken, message.LatestTime, message.Status = db.Login(userName, userPwd)
	} else {
		message.Status = -1
	}
	// 返回字段
	data, _ := json.Marshal(message)
	w.Header().Set("content-type", "text/json")
	w.Write(data)
}

// HTTPInterceptor : 拦截器
// func HTTPInterceptor(handler http.HandlerFunc) http.HandlerFunc {
// 	return http.HandlerFunc(
// 		func(w http.ResponseWriter, r *http.Request) {
// 			r.ParseForm()
// 			userName := r.Form.Get("userName")
// 			token := r.Form.Get("token")

// 			// token 验证
// 			suc := db.VerifyToken(userName, token)
// 			if !suc {
// 				w.WriteHeader(http.StatusForbidden)
// 				return
// 			}
// 			w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域
// 			w.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, cache-control,postman-token,Cookie, Accept,x-requested-with")
// 			w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, OPTIONS")
// 			// 正常处理请求
// 			handler(w, r)
// 		})
// }
